#include <Arduino.h>
#include <Servo.h>
#include <EEPROM.h>

#include <ESP8266mDNS.h>
#include <ESP8266WiFi.h>
#include <uri/UriBraces.h>
#include <SD.h>
#include "vue.h"

const char *ssid = WIFI_SSID;
const char *password = WIFI_PASSWORD;

Servo servo;

extern "C" {

struct range {
    uint8_t up;
    uint8_t down;
};

struct range servo_range = {
        70, 160
};

}


void lightSwitch();
void setRange();
void setLocation();

void setup() {
    Serial.begin(115200);
    while (!Serial) {}
    Serial.println("read flash ");
    // 尝试从flash中读取保存的范围
    EEPROM.begin(512);
    // 第一位表示是否存值,默认0xff
    if (EEPROM.read(0) == 1) {
        Serial.printf("has value");
        EEPROM.get(1, servo_range);
        Serial.printf("up and down in eeprom is: %d %d \n", servo_range.up, servo_range.down);
    }
    // sg90
    servo.attach(SERVO_PIN, 500, 2500);

    LittleFS.begin();
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(WiFi.status());
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);

    if (MDNS.begin(ESP8266_SEVER_HOST_NAME)) {
        Serial.println("MDNS responder started");
    }

    vueWebServer.on("/", handleRoot);
    vueWebServer.on("/favicon.ico", handleAssets);
    vueWebServer.on(LevelUri("/assets"), handleAssets);
    vueWebServer.on(LevelUri("/images"), handleAssets);
    vueWebServer.on(UriBraces("/lightSwitch/{}"), lightSwitch);
    vueWebServer.on(UriBraces("/setRange/{}"), setRange);
    vueWebServer.on(UriBraces("/setLocation/{}"), setLocation);
    vueWebServer.begin();
    Serial.println("HTTP server started");
    Serial.print("http://");
    Serial.println(WiFi.localIP());
}

void loop() {
    vueWebServer.handleClient();
    delay(2);
    MDNS.update();

}

void lightSwitch() {
    const String& pathArg = vueWebServer.pathArg(0);
    if(!pathArg){
        return;
    }
    int action = pathArg.toInt();
    servo.write(action == 0 ? servo_range.up : servo_range.down);
    delay(240);
    servo.write(90);
    vueWebServer.send(200, "text/html", "<script>window.close()</script>");
}

void setRange() {
    const String& pathArg = vueWebServer.pathArg(0);
    if(!pathArg){
        return;
    }
    int range = pathArg.toInt();
    if (range < 0 || range > 180) {
        return;
    }
    servo_range.up = range;
    servo_range.down = 180 - range;
    EEPROM.write(0, 1);
    EEPROM.put(1, servo_range);
    EEPROM.commit();
    vueWebServer.send(200, "text/plain", "ok");
}

void setLocation() {
    const String& pathArg = vueWebServer.pathArg(0);
    if(!pathArg){
        return;
    }
    int range = pathArg.toInt();
    if (range < 0 || range > 180) {
        return;
    }
    servo.write(range);
    vueWebServer.send(200, "text/plain", "ok");
}